//
//  OAuthViewController.swift
//  微博
//
//  Created by mac on 15/12/13.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class OAuthViewController: UIViewController {
    
    /**
    创建一个webView
    */
    let webView = UIWebView()
    /**
    网路请求的参数
    */
    let client_id = "1366606636"
    let redirect_uri = "http://www.baidu.com"
    let client_secret = "827b95b8f210011fed154d9ac4575fc5"
    override func loadView() {
        //把根视图替换webView
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "back")
        //设置webView的代理
       
        //创建一个urlstring
        loadOauthPage()
    }
    /**
    请求授权页面
    */
    func loadOauthPage() {
        //创建一个url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
    }
    /**
    返回控制器
    */
    @objc private func back() {
        dismissViewControllerAnimated(true, completion: nil)
    }


}


//代理方法
extension OAuthViewController : UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //回调完成的数据
    //Optional(https://m.baidu.com/?code=f1bc9942b9ba9c7b97f705563010f2c0&from=844b&vit=fps)
    //请求数据
    /*Optional(https://api.weibo.com/oauth2/authorize?client_id=1366606636&redirect_uri=http://www.baidu.com)
    Optional("client_id=1366606636&redirect_uri=http://www.baidu.com")
    */
    //授权页面
    //Optional(https://api.weibo.com/oauth2/authorize#)
    //注册页面
    /*Optional(http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=2crIGE&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D1366606636%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.baidu.com%26from%3D%26with_cookie%3D)
    */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.URL)
        guard let urlStr = request.URL?.absoluteString else {
            return false
        }
        
        if urlStr.hasPrefix("https://api.weibo.com") {
            return true
        }
        //不是返回页面全部取消
        if !urlStr.hasPrefix("http://www.baidu.com") {
            return false
        }
        
        let query = request.URL?.absoluteURL.query
        if let q = query {
            //获取access_token
            let str = "code="
            //获取对应字符串的使用包括code后面的下标
            let code = q.substringFromIndex(str.endIndex)
            print(code)
            loadAccess_token(code)
            //来获取access_token的数值
        }
        
        return true
    }
    
    private func loadAccess_token(code:String) {
        UserAccontViewMedol().loadAccess_token(code) { (success) -> () in
            if success == true {
                print("登录成功")
                //关闭model的窗口
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //跳转到
                    NSNotificationCenter.defaultCenter().postNotificationName(rootVC, object:"welcome")
                })
              
            }else {
                print("登录失败")
            }
        }
        
        
    }
    
    
    
   }


